using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Volo.Abp;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;
using Matrix.Notification.Domain.Shared.Notifications;

namespace Matrix.Notification.Domain.Notifications
{
    /// <summary>
    /// 通知订阅聚合根实体
    /// </summary>
    public class NotificationSubscription : FullAuditedAggregateRoot<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 用户ID
        /// </summary>
        public virtual Guid UserId { get; protected set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public virtual string UserName { get; protected set; } = string.Empty;

        /// <summary>
        /// 邮箱地址
        /// </summary>
        public virtual string? EmailAddress { get; protected set; }

        /// <summary>
        /// 手机号码
        /// </summary>
        public virtual string? PhoneNumber { get; protected set; }

        /// <summary>
        /// 订阅的通知类型（JSON格式）
        /// </summary>
        public virtual string SubscribedTypes { get; protected set; } = string.Empty;

        /// <summary>
        /// 启用的通知渠道（JSON格式）
        /// </summary>
        public virtual string EnabledChannels { get; protected set; } = string.Empty;

        /// <summary>
        /// 禁用的通知渠道（JSON格式）
        /// </summary>
        public virtual string DisabledChannels { get; protected set; } = string.Empty;

        /// <summary>
        /// 订阅的分类（JSON格式）
        /// </summary>
        public virtual string SubscribedCategories { get; protected set; } = string.Empty;

        /// <summary>
        /// 关键词过滤（JSON格式）
        /// </summary>
        public virtual string KeywordFilters { get; protected set; } = string.Empty;

        /// <summary>
        /// 时间限制配置（JSON格式）
        /// </summary>
        public virtual string TimeRestrictions { get; protected set; } = string.Empty;

        /// <summary>
        /// 频率限制配置（JSON格式）
        /// </summary>
        public virtual string FrequencyLimits { get; protected set; } = string.Empty;

        /// <summary>
        /// 是否启用
        /// </summary>
        public virtual bool IsEnabled { get; protected set; }

        /// <summary>
        /// 是否全局禁用
        /// </summary>
        public virtual bool IsGloballyDisabled { get; protected set; }

        /// <summary>
        /// 全局禁用原因
        /// </summary>
        public virtual string? GlobalDisableReason { get; protected set; }

        /// <summary>
        /// 全局禁用时间
        /// </summary>
        public virtual DateTime? GlobalDisabledTime { get; protected set; }

        /// <summary>
        /// 全局禁用截止时间
        /// </summary>
        public virtual DateTime? GlobalDisableExpiryTime { get; protected set; }

        /// <summary>
        /// 是否允许营销通知
        /// </summary>
        public virtual bool AllowMarketingNotifications { get; protected set; }

        /// <summary>
        /// 是否允许系统通知
        /// </summary>
        public virtual bool AllowSystemNotifications { get; protected set; }

        /// <summary>
        /// 是否允许安全通知
        /// </summary>
        public virtual bool AllowSecurityNotifications { get; protected set; }

        /// <summary>
        /// 默认优先级
        /// </summary>
        public virtual NotificationPriority DefaultPriority { get; protected set; }

        /// <summary>
        /// 每日最大接收数量
        /// </summary>
        public virtual int DailyMaxCount { get; protected set; }

        /// <summary>
        /// 今日已接收数量
        /// </summary>
        public virtual int TodayReceivedCount { get; protected set; }

        /// <summary>
        /// 最后统计日期
        /// </summary>
        public virtual DateTime? LastStatisticsDate { get; protected set; }

        /// <summary>
        /// 订阅设置（JSON格式）
        /// </summary>
        public virtual string? Settings { get; protected set; }

        /// <summary>
        /// 个性化配置（JSON格式）
        /// </summary>
        public virtual string? Personalization { get; protected set; }

        /// <summary>
        /// 设备偏好（JSON格式）
        /// </summary>
        public virtual string? DevicePreferences { get; protected set; }

        /// <summary>
        /// 语言偏好
        /// </summary>
        public virtual string LanguagePreference { get; protected set; } = "zh-CN";

        /// <summary>
        /// 时区偏好
        /// </summary>
        public virtual string TimeZonePreference { get; protected set; } = "Asia/Shanghai";

        /// <summary>
        /// 最后活跃时间
        /// </summary>
        public virtual DateTime? LastActiveTime { get; protected set; }

        /// <summary>
        /// 最后接收通知时间
        /// </summary>
        public virtual DateTime? LastNotificationTime { get; protected set; }

        /// <summary>
        /// 订阅标签
        /// </summary>
        public virtual string Tags { get; protected set; } = string.Empty;

        /// <summary>
        /// 备注信息
        /// </summary>
        public virtual string? Notes { get; protected set; }

        protected NotificationSubscription()
        {
        }

        /// <summary>
        /// 创建新订阅
        /// </summary>
        public NotificationSubscription(
            Guid id,
            Guid? tenantId,
            Guid userId,
            string userName,
            string? emailAddress = null,
            string? phoneNumber = null)
            : base(id)
        {
            TenantId = tenantId;
            UserId = userId;
            UserName = Check.NotNullOrWhiteSpace(userName, nameof(userName), maxLength: 100);
            EmailAddress = emailAddress;
            PhoneNumber = phoneNumber;
            IsEnabled = true;
            IsGloballyDisabled = false;
            AllowMarketingNotifications = false;
            AllowSystemNotifications = true;
            AllowSecurityNotifications = true;
            DefaultPriority = NotificationPriority.Normal;
            DailyMaxCount = 100;
            TodayReceivedCount = 0;
            LanguagePreference = "zh-CN";
            TimeZonePreference = "Asia/Shanghai";
        }

        /// <summary>
        /// 更新联系信息
        /// </summary>
        public virtual NotificationSubscription UpdateContactInfo(
            string userName,
            string? emailAddress = null,
            string? phoneNumber = null)
        {
            UserName = Check.NotNullOrWhiteSpace(userName, nameof(userName), maxLength: 100);
            EmailAddress = emailAddress;
            PhoneNumber = phoneNumber;
            return this;
        }

        /// <summary>
        /// 订阅通知类型
        /// </summary>
        public virtual NotificationSubscription SubscribeType(NotificationType type)
        {
            var types = GetSubscribedTypes();
            if (!types.Contains(type))
            {
                types.Add(type);
                UpdateSubscribedTypes(types);
            }
            return this;
        }

        /// <summary>
        /// 取消订阅通知类型
        /// </summary>
        public virtual NotificationSubscription UnsubscribeType(NotificationType type)
        {
            var types = GetSubscribedTypes();
            types.Remove(type);
            UpdateSubscribedTypes(types);
            return this;
        }

        /// <summary>
        /// 批量订阅通知类型
        /// </summary>
        public virtual NotificationSubscription SubscribeTypes(params NotificationType[] types)
        {
            var currentTypes = GetSubscribedTypes();
            foreach (var type in types)
            {
                if (!currentTypes.Contains(type))
                {
                    currentTypes.Add(type);
                }
            }
            UpdateSubscribedTypes(currentTypes);
            return this;
        }

        /// <summary>
        /// 启用通知渠道
        /// </summary>
        public virtual NotificationSubscription EnableChannel(NotificationChannel channel)
        {
            var enabledChannels = GetEnabledChannels();
            if (!enabledChannels.Contains(channel))
            {
                enabledChannels.Add(channel);
                UpdateEnabledChannels(enabledChannels);
            }

            var disabledChannels = GetDisabledChannels();
            disabledChannels.Remove(channel);
            UpdateDisabledChannels(disabledChannels);
            return this;
        }

        /// <summary>
        /// 禁用通知渠道
        /// </summary>
        public virtual NotificationSubscription DisableChannel(NotificationChannel channel)
        {
            var disabledChannels = GetDisabledChannels();
            if (!disabledChannels.Contains(channel))
            {
                disabledChannels.Add(channel);
                UpdateDisabledChannels(disabledChannels);
            }

            var enabledChannels = GetEnabledChannels();
            enabledChannels.Remove(channel);
            UpdateEnabledChannels(enabledChannels);
            return this;
        }

        /// <summary>
        /// 订阅分类
        /// </summary>
        public virtual NotificationSubscription SubscribeCategory(string category)
        {
            if (string.IsNullOrWhiteSpace(category))
            {
                return this;
            }

            var categories = GetSubscribedCategories();
            if (!categories.Contains(category))
            {
                categories.Add(category);
                UpdateSubscribedCategories(categories);
            }
            return this;
        }

        /// <summary>
        /// 取消订阅分类
        /// </summary>
        public virtual NotificationSubscription UnsubscribeCategory(string category)
        {
            var categories = GetSubscribedCategories();
            categories.Remove(category);
            UpdateSubscribedCategories(categories);
            return this;
        }

        /// <summary>
        /// 启用订阅
        /// </summary>
        public virtual NotificationSubscription Enable()
        {
            IsEnabled = true;
            return this;
        }

        /// <summary>
        /// 禁用订阅
        /// </summary>
        public virtual NotificationSubscription Disable()
        {
            IsEnabled = false;
            return this;
        }

        /// <summary>
        /// 全局禁用
        /// </summary>
        public virtual NotificationSubscription GlobalDisable(string reason, DateTime? expiryTime = null)
        {
            IsGloballyDisabled = true;
            GlobalDisableReason = reason;
            GlobalDisabledTime = DateTime.UtcNow;
            GlobalDisableExpiryTime = expiryTime;
            return this;
        }

        /// <summary>
        /// 取消全局禁用
        /// </summary>
        public virtual NotificationSubscription CancelGlobalDisable()
        {
            IsGloballyDisabled = false;
            GlobalDisableReason = null;
            GlobalDisabledTime = null;
            GlobalDisableExpiryTime = null;
            return this;
        }

        /// <summary>
        /// 设置营销通知偏好
        /// </summary>
        public virtual NotificationSubscription SetMarketingPreference(bool allowMarketing)
        {
            AllowMarketingNotifications = allowMarketing;
            return this;
        }

        /// <summary>
        /// 设置系统通知偏好
        /// </summary>
        public virtual NotificationSubscription SetSystemNotificationPreference(bool allowSystem)
        {
            AllowSystemNotifications = allowSystem;
            return this;
        }

        /// <summary>
        /// 设置安全通知偏好
        /// </summary>
        public virtual NotificationSubscription SetSecurityNotificationPreference(bool allowSecurity)
        {
            AllowSecurityNotifications = allowSecurity;
            return this;
        }

        /// <summary>
        /// 设置默认优先级
        /// </summary>
        public virtual NotificationSubscription SetDefaultPriority(NotificationPriority priority)
        {
            DefaultPriority = priority;
            return this;
        }

        /// <summary>
        /// 设置每日最大接收数量
        /// </summary>
        public virtual NotificationSubscription SetDailyMaxCount(int maxCount)
        {
            if (maxCount < 0)
            {
                throw new ArgumentException("每日最大接收数量不能小于0", nameof(maxCount));
            }

            DailyMaxCount = maxCount;
            return this;
        }

        /// <summary>
        /// 增加今日接收数量
        /// </summary>
        public virtual NotificationSubscription IncrementTodayReceivedCount(int count = 1)
        {
            TodayReceivedCount += count;
            LastStatisticsDate = DateTime.UtcNow;
            return this;
        }

        /// <summary>
        /// 重置今日接收数量
        /// </summary>
        public virtual NotificationSubscription ResetTodayReceivedCount()
        {
            TodayReceivedCount = 0;
            LastStatisticsDate = DateTime.UtcNow;
            return this;
        }

        /// <summary>
        /// 检查是否超出每日限制
        /// </summary>
        public virtual bool IsDailyLimitExceeded()
        {
            return DailyMaxCount > 0 && TodayReceivedCount >= DailyMaxCount;
        }

        /// <summary>
        /// 检查是否可以接收通知
        /// </summary>
        public virtual bool CanReceiveNotification(NotificationType type, NotificationChannel channel)
        {
            if (!IsEnabled || IsGloballyDisabled)
            {
                return false;
            }

            // 检查通知类型订阅
            var subscribedTypes = GetSubscribedTypes();
            if (subscribedTypes.Count > 0 && !subscribedTypes.Contains(type))
            {
                return false;
            }

            // 检查渠道是否启用
            var enabledChannels = GetEnabledChannels();
            var disabledChannels = GetDisabledChannels();

            if (enabledChannels.Count > 0 && !enabledChannels.Contains(channel))
            {
                return false;
            }

            if (disabledChannels.Contains(channel))
            {
                return false;
            }

            // 检查特定类型的通知偏好
            switch (type)
            {
                case NotificationType.Marketing:
                    return AllowMarketingNotifications;
                case NotificationType.System:
                case NotificationType.Maintenance:
                    return AllowSystemNotifications;
                case NotificationType.Security:
                    return AllowSecurityNotifications;
                default:
                    return true;
            }
        }

        /// <summary>
        /// 设置语言偏好
        /// </summary>
        public virtual NotificationSubscription SetLanguagePreference(string language)
        {
            LanguagePreference = Check.NotNullOrWhiteSpace(language, nameof(language));
            return this;
        }

        /// <summary>
        /// 设置时区偏好
        /// </summary>
        public virtual NotificationSubscription SetTimeZonePreference(string timeZone)
        {
            TimeZonePreference = Check.NotNullOrWhiteSpace(timeZone, nameof(timeZone));
            return this;
        }

        /// <summary>
        /// 更新最后活跃时间
        /// </summary>
        public virtual NotificationSubscription UpdateLastActiveTime()
        {
            LastActiveTime = DateTime.UtcNow;
            return this;
        }

        /// <summary>
        /// 更新最后接收通知时间
        /// </summary>
        public virtual NotificationSubscription UpdateLastNotificationTime()
        {
            LastNotificationTime = DateTime.UtcNow;
            return this;
        }

        /// <summary>
        /// 设置关键词过滤
        /// </summary>
        public virtual NotificationSubscription SetKeywordFilters(string keywordFilters)
        {
            KeywordFilters = keywordFilters;
            return this;
        }

        /// <summary>
        /// 设置时间限制
        /// </summary>
        public virtual NotificationSubscription SetTimeRestrictions(string timeRestrictions)
        {
            TimeRestrictions = timeRestrictions;
            return this;
        }

        /// <summary>
        /// 设置频率限制
        /// </summary>
        public virtual NotificationSubscription SetFrequencyLimits(string frequencyLimits)
        {
            FrequencyLimits = frequencyLimits;
            return this;
        }

        /// <summary>
        /// 设置个性化配置
        /// </summary>
        public virtual NotificationSubscription SetPersonalization(string personalization)
        {
            Personalization = personalization;
            return this;
        }

        /// <summary>
        /// 设置设备偏好
        /// </summary>
        public virtual NotificationSubscription SetDevicePreferences(string devicePreferences)
        {
            DevicePreferences = devicePreferences;
            return this;
        }

        /// <summary>
        /// 设置标签
        /// </summary>
        public virtual NotificationSubscription SetTags(string tags)
        {
            Tags = tags ?? string.Empty;
            return this;
        }

        /// <summary>
        /// 设置备注
        /// </summary>
        public virtual NotificationSubscription SetNotes(string notes)
        {
            Notes = notes;
            return this;
        }

        /// <summary>
        /// 检查是否需要重置今日统计
        /// </summary>
        public virtual bool ShouldResetDailyStatistics()
        {
            if (!LastStatisticsDate.HasValue)
            {
                return true;
            }

            var lastDate = LastStatisticsDate.Value.Date;
            var currentDate = DateTime.UtcNow.Date;
            return lastDate < currentDate;
        }

        /// <summary>
        /// 获取订阅的通知类型
        /// </summary>
        public virtual List<NotificationType> GetSubscribedTypes()
        {
            var types = new List<NotificationType>();
            if (!string.IsNullOrEmpty(SubscribedTypes))
            {
                var typeStrings = SubscribedTypes.Split(',');
                foreach (var typeString in typeStrings)
                {
                    if (Enum.TryParse<NotificationType>(typeString.Trim(), out var type))
                    {
                        types.Add(type);
                    }
                }
            }
            return types;
        }

        /// <summary>
        /// 获取启用的通知渠道
        /// </summary>
        public virtual List<NotificationChannel> GetEnabledChannels()
        {
            var channels = new List<NotificationChannel>();
            if (!string.IsNullOrEmpty(EnabledChannels))
            {
                var channelStrings = EnabledChannels.Split(',');
                foreach (var channelString in channelStrings)
                {
                    if (Enum.TryParse<NotificationChannel>(channelString.Trim(), out var channel))
                    {
                        channels.Add(channel);
                    }
                }
            }
            return channels;
        }

        /// <summary>
        /// 获取禁用的通知渠道
        /// </summary>
        public virtual List<NotificationChannel> GetDisabledChannels()
        {
            var channels = new List<NotificationChannel>();
            if (!string.IsNullOrEmpty(DisabledChannels))
            {
                var channelStrings = DisabledChannels.Split(',');
                foreach (var channelString in channelStrings)
                {
                    if (Enum.TryParse<NotificationChannel>(channelString.Trim(), out var channel))
                    {
                        channels.Add(channel);
                    }
                }
            }
            return channels;
        }

        /// <summary>
        /// 获取订阅的分类
        /// </summary>
        public virtual List<string> GetSubscribedCategories()
        {
            var categories = new List<string>();
            if (!string.IsNullOrEmpty(SubscribedCategories))
            {
                categories.AddRange(SubscribedCategories.Split(',').Select(c => c.Trim()));
            }
            return categories;
        }

        /// <summary>
        /// 更新订阅的通知类型
        /// </summary>
        protected virtual void UpdateSubscribedTypes(List<NotificationType> types)
        {
            var typeList = types.Select(t => t.ToString());
            SubscribedTypes = string.Join(",", typeList);
        }

        /// <summary>
        /// 更新启用的通知渠道
        /// </summary>
        protected virtual void UpdateEnabledChannels(List<NotificationChannel> channels)
        {
            var channelList = channels.Select(c => c.ToString());
            EnabledChannels = string.Join(",", channelList);
        }

        /// <summary>
        /// 更新禁用的通知渠道
        /// </summary>
        protected virtual void UpdateDisabledChannels(List<NotificationChannel> channels)
        {
            var channelList = channels.Select(c => c.ToString());
            DisabledChannels = string.Join(",", channelList);
        }

        /// <summary>
        /// 更新订阅的分类
        /// </summary>
        protected virtual void UpdateSubscribedCategories(List<string> categories)
        {
            SubscribedCategories = string.Join(",", categories);
        }
    }
}